import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Animated,
  Dimensions,
  TouchableOpacity
} from 'react-native';
import styles from './cardIndexStyle';
import Touch from '../global/Touch';
import SimpleDialog from '../global/SimpleViewDialog';
import PasswordInput from '../global/PasswordInput';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';

const Wwidth = Dimensions.get('window').width;
const percent = 0.078125; // 弹窗左右间距百分比
let margin = Wwidth * percent; // 弹窗左右间距
let pwdWidth = Wwidth * (1 - percent * 2) * percent * 10; // 密码框长度
let padding = (Wwidth - 2 * margin - pwdWidth) / 2; // 关闭icon的右间距padding

// 银行卡route信息
let cardRoute = {
    title: "添加银行卡",
    backButtonTitle:'',
    screen: 'housekeeperapp.hkbindcard',
    passProps: {
        // orderId
    },
    navigatorStyle:{
        navBarHidden: false,
        tabBarHidden: true,
        navBarTextColor: 'white',
        navBarButtonColor: 'white',
        navBarBackgroundColor: '#EA5404',
        statusBarColor: '#EA5404',
        navBarTitleTextCentered: true,
        topBarElevationShadowEnabled:false
    },
    navigatorButtons: {
        leftButtons:[
            {
                id: 'back',
                icon: require("../../../img/hk_back_icon.png")
            }
        ]
    }
    // backButtonHidden: true,
}

class CardIndex extends Component {
    constructor(props) {
		super(props);

		this.state = {
            scrollY: new Animated.Value(0),
            isLoading: true, // 界面正在加载
            open: false,
            disable: false,
            isUnbindVisible: false,
            cardInfo: null,
            errorText: '', // 错误信息
            isChangeCardVisible: this.props.showChangeDialog || false, // 是否显示更换银行卡弹窗
		};
	}

    componentDidMount() {
        this._fetchCardInfo();
	}

    componentWillReceiveProps(nextProps) {
        this._fetchCardInfo();
        // 关闭弹窗
        this.setState({isChangeCardVisible:false,open:false,isLoading:true})
    }

    async _fetchCardInfo() {
        let res = await api.post("/card/mycard",{});

        if(res.data){//已绑卡
            this.setState({
                isLoading:false,
                cardInfo:res.data
            });
        } else {
            this.setState({
                isLoading:false
            });
        }
    }

    _addCard() {
        let {cardInfo} = this.state;
        let {session} = this.props;
        if (session.user && session.user.withdraw_password) {
            this.props.navigator.push(cardRoute);
        } else {
            this.setState({open:true});
        }
    }

    _closeAction() {
        this.setState({open:false});
    }

    _payAction() {
    }

    async _showUnbindDialog() {
        let {cardInfo} = this.state;
        let {session} = this.props;
        if (session.user && session.user.withdraw_password) {
            this.setState({isUnbindVisible:true});
        } else {
            let data = await api.post("/card/unbindCard",{id:cardInfo.id});
            if (data && data.cd == 0) {
                this.setState({isUnbindVisible:false,cardInfo:null},()=>{
                    this.refs.toast.show('解绑成功');
                });
                this._fetchCardInfo();
            }
        }

    }

    _renderDialog() {
        let {errorText} = this.state;
        let disable = false;
        return (
            <SimpleDialog
                offset={this.state.offset}
                open={this.state.open}
                closeOnTouchOutside={false}
                modalStyle={{padding:0,margin,overflow:'hidden'}}
                modalDidOpen={() => console.log('modal did open')}
                style={{alignItems: 'center'}}>
                    <View style={styles.dialogContainer}>
                        <View style={styles.dialogTitle}>
                            <Text style={styles.dialogTitleText}>
                                请设置提现密码
                            </Text>
                        </View>
                        <TouchableOpacity onPress={this._closeAction.bind(this)} style={styles.closeIcon}>
                            <Image source={require('../../../img/dialog_close.png')}/>
                        </TouchableOpacity>
                        <View style={{alignItems:'center',marginTop:20}}>
                            <PasswordInput hiddeCursor={true} ref="pwdinput" type="SET_WITHDRAW_PASSWORD" errorText={errorText} width={pwdWidth}/>
                        </View>
                        <View style={[styles.submitBtnContainer,{marginTop:10,marginLeft:padding,marginRight:padding},disable?{backgroundColor:'#DEDEDE'}:{}]}>
                            <Touch onPress={disable?null:this._setWithdrawPwdAction.bind(this)} style={styles.submitBtn}>
                                <Text style={[styles.submitBtnText,disable?{color:'#f5f5f5'}:{}]}>确定</Text>
                            </Touch>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }

    _renderChangeDialog() {
        let {session} = this.props;
        let {errorText} = this.state;
        let disable = false;
        return (
            <SimpleDialog
                offset={this.state.offset}
                open={this.state.isChangeCardVisible}
                closeOnTouchOutside={false}
                modalStyle={{padding:0,margin,overflow:'hidden'}}
                modalDidOpen={() => console.log('modal did open')}
                style={{alignItems: 'center'}}>
                    <View style={styles.dialogContainer}>
                        <View style={styles.dialogTitle}>
                            <Text style={styles.dialogTitleText}>
                                更换银行卡
                            </Text>
                        </View>
                        <TouchableOpacity onPress={()=>{this.setState({isChangeCardVisible:false})}} style={styles.closeIcon}>
                            <Image source={require('../../../img/dialog_close.png')}/>
                        </TouchableOpacity>
                        <View style={{alignItems:'center',marginTop:20}}>
                            <PasswordInput  hiddeCursor={true} ref="pwdinput" errorText={errorText} tipText="请输入提现密码，以验证身份" width={pwdWidth}/>
                        </View>
                        <View style={[styles.submitBtnContainer,{marginTop:10,marginLeft:padding,marginRight:padding},disable?{backgroundColor:'#DEDEDE'}:{}]}>
                            <Touch onPress={disable?null:this._changeCardAction.bind(this)} style={styles.submitBtn}>
                                <Text style={[styles.submitBtnText,disable?{color:'#f5f5f5'}:{}]}>确定</Text>
                            </Touch>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }
    async _setWithdrawPwdAction(password) {
        password = password || this.refs.pwdinput.state.password;
        let {session,actions,dispatch} = this.props;
        // 密码不符合规范
        if (this.refs.pwdinput.password.length == 6) {
            if (password != this.refs.pwdinput.password) {
                this.setState({errorText:'两次输入不一致，请重新输入'});
                return;
            }
        } else {
            this.setState({errorText:'请输入6位数字密码'});
            return;
        }

        let res = await api.post("/housekeeper/setWithdrawPwd",{pwd:password,pwd_confirm:password});

        if(res.cd == 1){
            this.refs.toast.show(res.msg);
            return;
        }
        console.log("###", res);

        if (res.data) {
            this.setState({open:false},()=>{
                this.refs.toast.show('设置成功');
                // 更新本地用户状态
                dispatch(actions.session.session_change({
                    ticket:session.stoken,
                    userId:session.user.id,
                    reload: false,
                    group:session.user.group
                }));
                this.props.navigator.push(cardRoute);
            });
        }
    }

    // 显示更换银行卡弹窗
    _changeCard() {
        let {cardInfo} = this.state;
        let {session} = this.props;

        if (session.user && session.user.withdraw_password == null) {
            let route = Object.assign({},cardRoute,{
                title:'更换银行卡',
                passProps:{
                    type: 'CHANGE_CARD',
                    old_id:cardInfo.id
                }
            })
            this.props.navigator.push(route);
        } else {
            this.setState({isChangeCardVisible:true});
        }
    }
    // 更换银行卡
    async _changeCardAction() {
        let {cardInfo} = this.state;
        let {password} = this.refs.pwdinput.state;
        if (password.length == 6) {
            // 首先需要确认提现密码
            let res = await api.post("/housekeeper/validateWithdrawPwd",{pwd:password});
            if (res.cd == 0) {
                let route = Object.assign({},cardRoute,{
                    title:'更换银行卡',
                    passProps:{
                        type: 'CHANGE_CARD',
                        old_id:cardInfo.id
                    }
                })
                this.props.navigator.push(route);
            } else {
                this.setState({errorText:'请输入正确的密码'});
            }
        } else {
            this.setState({errorText:'请输入正确的密码'});
        }
    }

    // 解绑操作
    async _unbindAction() {
        let {cardInfo} = this.state;
        let {password} = this.refs.pwdinput;
        if (password.length == 6) {
            // 首先需要确认提现密码
            let res = await api.post("/housekeeper/validateWithdrawPwd",{pwd:password});
            if (res.cd == 0) {
                let data = await api.post("/card/unbindCard",{id:cardInfo.id});
                if (data.cd == 0) {
                    this.setState({isUnbindVisible:false,cardInfo:null},()=>{
                        this.refs.toast.show('解绑成功');
                    });
                }
            } else {
                this.setState({errorText:'请输入正确的密码'});
            }
        } else {
            this.setState({errorText:'请输入正确的密码'});
        }
    }

    _renderUnbindDialog() {
        let {offset,isUnbindVisible,errorText} = this.state;
        let disable = false;
        return (
            <SimpleDialog
                offset={offset}
                open={isUnbindVisible}
                closeOnTouchOutside={false}
                modalStyle={{padding:0,margin,overflow:'hidden'}}
                modalDidOpen={() => console.log('modal did open')}
                style={{alignItems: 'center'}}>
                    <View style={styles.dialogContainer}>
                        <View style={styles.dialogTitle}>
                            <Text style={styles.dialogTitleText}>
                                解绑银行卡
                            </Text>
                        </View>
                        <TouchableOpacity onPress={()=>this.setState({isUnbindVisible:false})} style={styles.closeIcon}>
                            <Image source={require('../../../img/dialog_close.png')}/>
                        </TouchableOpacity>

                        <View style={{alignItems:'center',marginTop:20}}>
                            <PasswordInput hiddeCursor={true} ref="pwdinput" errorText={errorText} tipText="请输入提现密码，以验证身份" width={pwdWidth}/>
                        </View>
                        <View style={[styles.submitBtnContainer,{marginTop:10,marginLeft:padding,marginRight:padding},disable?{backgroundColor:'#DEDEDE'}:{}]}>
                            <Touch onPress={disable?null:this._unbindAction.bind(this)} style={styles.submitBtn}>
                                <Text style={[styles.submitBtnText,disable?{color:'#f5f5f5'}:{}]}>确定</Text>
                            </Touch>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }

    _renderNoCard() {
        return (
            <ScrollView contentContainerStyle={styles.noData}>
                <Image source={require('../../../img/hk_addcard_icon.png')} style={styles.rightImage}/>
                <Text style={styles.noText}>
                    还未添加银行卡
                </Text>

                <Touch onPress={this._addCard.bind(this)}>
                    <View style={styles.addWithdraw}>
                        <Image style={styles.addWithdrawImage} source={require('../../../img/hk_add_task.png')} />
                        <Text style={styles.addWithdrawBtnText}>
                            添加银行卡
                        </Text>
                    </View>
                </Touch>
            </ScrollView>
        )

    }

    _submitAction(){
        let {actions, dispatch} = this.props;
        dispatch(actions.session.clear_session());
    }

    _renderCard() {
        let {cardInfo} = this.state;
        return (
            <View>
                <View style={styles.cardStyle}>
                    <View style={styles.cardHead}>
                        <Text style={styles.cardName}>{cardInfo && cardInfo.bankName}</Text>
                    </View>
                    <View style={styles.cardBottom}>
                        <Text style={styles.cardNumber}>**** **** **** *** {cardInfo&&cardInfo.bankCardNo.substring(cardInfo.bankCardNo.length-4)}</Text>
                    </View>
                </View>
                <View style={styles.cardHandler}>
                    <Touch onPress={this._changeCard.bind(this)} style={{alignItems:'flex-start',flex:1}}>
                        <Text style={styles.doText}>更换银行卡</Text>
                    </Touch>
                    <Touch onPress={this._showUnbindDialog.bind(this)} style={{alignItems:'flex-end',flex:1}}>
                        <Text style={styles.doText}>解除绑定</Text>
                    </Touch>
                </View>
            </View>
        )
    }

    render() {
        let {cardInfo,isLoading} = this.state;
        if (isLoading) {
            return null;
        }
        return (
            <View style={styles.container}>
                {
                    cardInfo ? this._renderCard() : this._renderNoCard()
                }
                {
                    cardInfo ? this._renderChangeDialog() : this._renderDialog()
                }
                {this._renderUnbindDialog()}
                <ToastTip ref="toast" offsetY={160}/>
            </View>
        )
    }
}

var connectHelper = require('../../services/connectHelper');
CardIndex = connectHelper(state => state)(CardIndex);

module.exports = CardIndex;
